/*
 * Copyright (c) 2021 Martin Koster
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.github.actionfx.core.bind;

import java.util.ArrayList;
import java.util.List;

import com.github.actionfx.core.beans.BeanPropertyReference;
import com.github.actionfx.core.beans.BeanWrapper;
import com.github.actionfx.core.view.graph.ControlWrapper;

/**
 * Proxy around a model class that is used for form binding.
 *
 * @author koster
 *
 */
public class BindingModelProxy extends BeanWrapper {

	private final List<BindingTarget> bindingTargets = new ArrayList<>();

	private final List<Binding> activeBindings = new ArrayList<>();

	public BindingModelProxy(final Object model, final List<BindingTarget> bindingTargets) {
		super(model);
		this.bindingTargets.addAll(bindingTargets);
	}

	/**
	 * Performs a binding between the {@code model} and the supplied
	 * {@code bindingTargets}.
	 */
	public void bind() {
		for (final BindingTarget bindingTarget : bindingTargets) {
			final BeanPropertyReference<?> reference = getBeanPropertyReference(bindingTarget.getBeanPathExpression());
			// in case one of the path elements in "beanPathExpression" resolved to null, a
			// return value of null needs to be handled
			if (reference == null) {
				continue;
			}
			final ControlWrapper controlWrapper = ControlWrapper.of(bindingTarget.getControl());
			activeBindings.add(controlWrapper.bind(reference, bindingTarget.getTargetProperty(),
					bindingTarget.getFormatPattern()));
		}
	}

	/**
	 * Unbinds all {@code bindingTargets} again from the supplied {@code model}.
	 */
	public void unbind() {
		activeBindings.forEach(Binding::unbind);
	}
}
